const fs = require('fs');

const axios = require('axios');
const path = require('path');
const sql = require('../PutArticle/model/MySQL');
const createPage = require('../Puppeteer/Puppeteer');
const { uploadImage } = require('../uploadImage/uploadImage');
const fsPromises = require('fs').promises;

const randomDelay = Math.floor(Math.random() * 3000) + 1000;

const dataArr = {
  game_icon: '',
  class_name: '',
};

const URL = 'https://play.google.com/store/apps/details?id=com.roblox.client'
async function GP_Icon(URL) {
  const { globalBrowser, page } = await createPage();


  try {
    await page.goto(URL, {
      timeout: 0,
    });

    if (!page) {
      console.error('Error: Evaluation failed: ReferenceError: page is not defined');
      return;
    }

    const result = await processPageData(page);
    console.log(result);
    return Promise.resolve(result);
  } catch (error) {
    console.error('爬取失败:', error);
  } finally {
    await page.close();
    const pages = await globalBrowser.pages();
  }
}

async function processPageData(page) {
  await page.waitForTimeout(randomDelay);

  const url = page.url();
  const id = url.match(/\?id=(.*)/)[1];
  dataArr.class_name = id;

  const gameIconSelector = ['div.qxNhq img', '.Il7kR img'];
  let gameIcon = null;

  for (const selector of gameIconSelector) {
    gameIcon = await page.$eval(selector, (img) => img.src).catch(() => null);
    if (gameIcon) {
      console.log('游戏图标:', gameIcon);
      await icon(gameIcon);
      break;
    }
  }

  if (!gameIcon) {
    console.log('未找到游戏图标');
  }
  async function icon(imageUrl) {
    console.log('开始下载图片：' + imageUrl);
    const response = await axios.get(imageUrl, {
      responseType: 'stream',
      timeout: 5000,
    });
    const randomNum = Math.floor(Math.random() * 1000);
    const fileName = `image_${id}_icon_${randomNum}.jpg`;
    const filePath = path.join(path.join(__dirname, 'img'), fileName);
    const writer = fs.createWriteStream(filePath);

    response.data.pipe(writer);

    await new Promise((resolve, reject) => {
      writer.on('finish', async () => {
        console.log(`已下载图片：${filePath}`);
        try {
          const uploadResponse = await uploadImage(filePath);
          console.log(uploadResponse.url);

          // 更新数据和数据库
          dataArr.game_icon = uploadResponse.url;
          console.log(dataArr);
          sql.updateGameIcon(dataArr.class_name, uploadResponse.url);

          // 删除本地文件
          await fsPromises.unlink(filePath);

          resolve();
        } catch (error) {
          console.error('上传失败，错误信息：', error);
          reject(error);
        }
      });

      writer.on('error', (error) => {
        console.error(`下载图片 ${imageUrl} 失败：${error}`);
        resolve();
      });
    });
  }

  return Promise.resolve('完成');
}

// GP_Icon(URL)
module.exports = GP_Icon;
